<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="功能房名" prop="roomName">
        <el-input v-model="queryParams.roomName" placeholder="请输入功能房名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="AddReservation">预约功能房</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :border="true" :data="roomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" />
      <el-table-column label="序号" prop="id" />
      <el-table-column label="名称" prop="roomName" />
      <el-table-column label="容纳人数" prop="roomCapacity" />
      <el-table-column label="使用事项" prop="roomMatter" />
      <el-table-column label="照片" prop="rtFuResourcesList">
        <template slot-scope="scope">
          <div class="images">
            <template v-if="scope.row.rtFuResourcesList && scope.row.rtFuResourcesList.length > 0">
              <el-image style="width: 100px; height: 100px;"
                :src="baseUrl + scope.row.rtFuResourcesList[0].resPath.split(',')[0]"></el-image>
            </template>
            <template v-else>
              <span>没有照片</span>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />


    <!-- 查看使用情况弹出框 -->
    <!-- <el-dialog title="请选择时间" :visible.sync="selectTime" append-to-body v-if="form !== null">
      <el-dialog :title="title" :visible.sync="detail" append-to-body>
        <div style="padding: 20px;" v-if="fuDetailList.Wek">
          <div style="display: flex;" v-if="fuDetailList && fuDetailList.Wek">
            <strong style="margin-right: 50px;">日期</strong>
            <span v-for="(itemday, index) in fuDetailList.Wek.day" :key="index" style="margin-bottom: 5px;">
              {{ itemday }}
            </span>
          </div>
          <div v-if="fuDetailList && fuDetailList.Wek" style="display: flex; flex-wrap: nowrap; ">
            <div style="margin-right: 30px;" v-for="(yuyue, yIndex) in fuDetailList.Wek.yuyue" :key="yIndex">
              <div style="margin-bottom: 6px;"><strong style="margin-right: 45px; ">时间</strong> {{ yuyue }}</div>
              <div> <strong style="margin-right: 35px; margin-top: 50px;">使用人</strong>{{ fuDetailList.Wek.user[yIndex]
                }}
              </div>
            </div>
          </div>
          <div style="position: absolute; bottom: 20px; right: 20px;">
            <el-button @click="detail = false" style="margin-right: 0;">取消</el-button>
          </div>
        </div>
        <div v-else>
          当天没人预约
        </div>
      </el-dialog>
      <div class="block">
        <span class="demonstration">默认</span>
        <el-date-picker v-model="timeValue" type="date" placeholder="选择日期">
        </el-date-picker>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectTime = false">取消</el-button>
        <el-button @click="goDetail()">提交</el-button>
      </div>
    </el-dialog> -->
    <!-- 功能房预约 -->
    <el-dialog title="功能房预约" :visible.sync="reServation">
      <el-dialog title="预约时间段" :visible.sync="selectDate" append-to-body>
        <div>
          <div>
            <el-date-picker v-model="rtYuyue" type="date" placeholder="选择日期"
              :picker-options="{ disabledDate: disabledDate }" @change="confirmAppointment"></el-date-picker>
          </div>
          <div>
            <el-radio-group v-model="selectedTime" style="display: flex">
              <el-radio-button v-for="(item, index) in timeList" :key="index" :label="item" style="margin-top: 20px;">
                {{ item }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="selectDate = false">取消</el-button>
          <el-button @click="sub">确定</el-button>
        </div>
      </el-dialog>
      <div style="padding: 20px;">
        <el-form ref="reservationForm" :model="reservationForm" :rules="reservationRules" label-width="120px">
          <el-form-item label="功能房名称">
            <div>{{ selectedRoomName }}</div>
          </el-form-item>
          <el-form-item label="主题" prop="rtTheme">
            <el-input v-model="reservationForm.rtTheme" placeholder="请输入主题" style="width: 360px;" />
          </el-form-item>
          <el-form-item label="参与人员类型" prop="rtRole">
            <el-select v-model="reservationForm.rtRole" placeholder="请选择参与人员类型" style="width: 360px;">
              <el-option label="学校领导" value="学校领导"></el-option>
              <el-option label="部门/学院领导" value="部门/学院领导"></el-option>
              <el-option label="辅导员" value="辅导员"></el-option>
              <el-option label="专任老师" value="专任老师"></el-option>
              <el-option label="行政人员" value="行政人员"></el-option>
              <el-option label="学生" value="学生"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="参与人数" prop="rtPeople">
            <el-input v-model="reservationForm.rtPeople" placeholder="参与容纳人数" style="width: 360px;" />
          </el-form-item>
          <el-form-item label="预约时间段" prop="selectedTime">
            <el-button v-model="selectedTime" style="width: 360px;" @click="selectRulesDate()">
              {{ selectedTime ? selectedTime : '请选择预约时间段' }}
            </el-button>
          </el-form-item>
          <el-form-item label="预约用途" prop="rtPurpose">
            <el-input type="textarea" v-model="reservationForm.rtPurpose" :rows="4" placeholder="请输入预约用途"
              style="width: 360px;">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reServation = false">取消</el-button>
        <el-button type="primary" @click="validateAndSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRoom, getRoom, delRoom, addRoom, updateRoom, updateStatus, getfuDetail, getfuTime } from "@/api/routine/room";
import { addReservation, selectRtFuReservationTime } from "@/api/routine/reservation";
export default {
  name: "Room",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 功能房表格数据
      roomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roNo: null,
        roomName: null,
        roomPlace: null,
        roomImg: null,
        roomInfo: null,
        roomPurp: null,
        status: null,
        roomCapacity: null,
        roomOpen: null,
        roomMatter: null
      },
      // 表单参数
      form: {},
      rtTime: '',
      rtYuyue: '',
      reservationForm: {
        rtTheme: '',
        rtRole: '',
        rtPeople: '',
        rtPurpose: '',
        roNo: '',
      },
      // 表单校验
      reservationRules: {
        rtTheme: [{ required: true, message: '请输入主题', trigger: 'blur' }],
        rtRole: [{ required: true, message: '请选择参与人员类型', trigger: 'change' }],
        rtPeople: [{ required: true, message: '请输入参与人数', trigger: 'blur' }],
        rtPurpose: [{ required: true, message: '请输入预约用途', trigger: 'blur' }],
      },
      reServation: false,
      detail: false,
      startTimeValue: '',
      endTimeValue: '',
      fuDetailList: [],
      cities: [],
      textarea: '',
      activeName: '',
      radio: '',
      radio4: '规则一',
      selectedRoomId: '',
      formattedDate: '',
      setRuleDialog: false,
      selectedRoomName: '',
      baseUrl: process.env.VUE_APP_BASE_API,
      selectDate: false,
      roType: '',
      rulesList: [],
      selectedRoomRono: '',
      selectedAppointmentTime: '', // 用来存储选择的预约时间段
      timeList: [],
      selectedTime: ''
    };
  },
  created() {
    this.getList();
    // 在Vue组件或其他代码中获取target的值
  },
  methods: {
    /** 查询功能房列表 */
    getList() {
      this.loading = true;
      console.log("list")
      listRoom(this.queryParams).then(response => {
        this.roomList = response.rows
        console.log(this.roomList);
        this.total = response.total;
        this.loading = false;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        roomName: null,
        roomPlace: null,
        roomImg: null,
        roomInfo: null,
        roomPurp: null,
        status: null,
        roomCapacity: null,
        roomOpen: null,
        roomMatter: null,
      };
      this.radio = ''; // 重置单选按钮组
      this.resetForm("form"); // 重置表单验证状态
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    //功能房状态开关
    handleCheckUsage(id) {
      // 设置选中的功能房id
      this.selectedRoomId = id;
      // 显示选择时间对话框
      this.selectTime = true;
    },

    /** 提交查看使用情况 */
    goDetail() {
      var dateObject = new Date(this.timeValue);
      var year = dateObject.getFullYear();
      var month = (dateObject.getMonth() + 1).toString().padStart(2, '0');
      var day = dateObject.getDate().toString().padStart(2, '0');
      this.formattedDate = `${year}-${month}-${day}`;
      getfuDetail(this.selectedRoomId, this.formattedDate).then(response => {
        this.fuDetailList = response.data;
      })
      // 关闭选择时间对话框
      this.title = "当前日期功能房使用情况"
      this.selectTime = false;
      this.detail = true;
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      if (selection.length > 0) {
        const selectedRoom = selection[0]; // 只允许单选，取第一个选择项
        this.selectedRoomName = selectedRoom.roomName;
        this.selectedRoomRono = selectedRoom.roNo;
      } else {
        this.selectedRoomName = ''; // 如果没有选中项，则清空显示
      }
    },
    goReservation() {
      this.$router.push({
        path: 'index'
      })
    },

    // 提交预约功能房表单，并进行验证
    validateAndSubmit() {
      this.$refs.reservationForm.validate(valid => {
        if (valid) {
          // 表单验证通过，可以提交数据
          const today = new Date();
          const year = today.getFullYear();
          const month = String(today.getMonth() + 1).padStart(2, '0');
          const day = String(today.getDate()).padStart(2, '0');
          const currentDate = `${year}-${month}-${day}`;

          const requestData = {
            roomName: this.selectedRoomName,
            rtTheme: this.reservationForm.rtTheme,
            rtRole: this.reservationForm.rtRole,
            rtPurpose: this.reservationForm.rtPurpose,
            rtPeople: this.reservationForm.rtPeople,
            rtYuyue: this.selectedTime,
            roNo:this.selectedRoomRono,
            rtTime: currentDate,
          };
          // console.log(requestData)
          addReservation(requestData).then(response => {
            console.log(response)
            if(response.msg == "预约成功"){
              this.$message.success("预约功能房成功！");
            this.reServation = false;
            this.resetReservationForm();
            }else{
              this.$message.error("功能房当前时间段已被预约");
            }
          })
        } else {
          // 表单验证未通过，不执行提交操作
          return false;
        }
      });
    },

    // 重置预约功能房表单字段
    resetReservationForm() {
      this.reservationForm.rtTheme = '';
      this.reservationForm.rtRole = '';
      this.reservationForm.rtPeople = '';
      this.reservationForm.rtPurpose = '';
      this.selectedTime = '';
    },


    AddReservation() {
          this.reServation = true;
        
    },
    selectRulesDate() {
      this.selectDate = true;
    },
    confirmAppointment() {
      const selectedDate = new Date(this.rtYuyue);
      const year = selectedDate.getFullYear();
      const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
      const day = String(selectedDate.getDate()).padStart(2, '0');
      const formattedDate = `${year}-${month}-${day}`;
      selectRtFuReservationTime(this.selectedRoomRono, formattedDate).then(res => {
        this.timeList = res.data.wek.Slots
      })
    },

    sub() {
      this.selectDate = false
    },
    // 禁用日期选择的函数，确保只能选择从今天开始的两周内日期
    disabledDate(time) {
      const today = new Date();
      const twoWeeksLater = new Date(today.getTime() + 14 * 24 * 60 * 60 * 1000);
      return time.getTime() < today.getTime() || time.getTime() > twoWeeksLater.getTime();
    }
  }
};
</script>